package com.geqian.web.log;

import com.geqian.web.entity.ApiLog;
import com.geqian.web.mapper.ApiLogMapper;
import com.geqian.web.pojo.DetailedLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author geqian
 * @date 13:55 2023/12/23
 */
@Component
public class ApiLogHandler {

    @Resource
    private ApiLogMapper apiLogMapper;

    private final Logger log = LoggerFactory.getLogger(ApiLogHandler.class);

    private static final BlockingQueue<DetailedLog> logQueue = new LinkedBlockingQueue<>();


    @Scheduled(fixedDelay = 500)
    private void handleLog() {
        for (int i = 0; i < getSize(); i++) {
            //队列中取出日志
            DetailedLog detailedLog = popLog();
            //保存日志到数据库
            saveLog(detailedLog);
            //格式化并输出日志
            printLog(detailedLog);
        }
    }

    /**
     * 保存日志
     *
     * @param detailedLog
     */
    private void saveLog(DetailedLog detailedLog) {

        ApiLog apiLog = new ApiLog();

        BeanUtils.copyProperties(detailedLog, apiLog);
        //保存日志
        this.apiLogMapper.insert(apiLog);
    }


    /**
     * 输出日志
     *
     * @param detailedLog
     */
    private void printLog(DetailedLog detailedLog) {
        StringBuilder sb = new StringBuilder("\n");
        sb.append("\n");
        sb.append("-----------------------------请求开始---------------------------------").append("\n");
        sb.append("请求时间: ").append(detailedLog.getAccessTime()).append("\n");
        sb.append("请求方式: ").append(detailedLog.getRequestMethod()).append("\n");
        sb.append("请求IP : ").append(detailedLog.getIp()).append("\n");
        sb.append("请求路径: ").append(detailedLog.getUrl()).append("\n");
        sb.append("请求参数: ").append(detailedLog.getParameters()).append("\n");
        sb.append("方法路径: ").append(detailedLog.getApiMethod()).append("\n");
        sb.append("请求头 : ").append(detailedLog.getHeaders()).append("\n");
        sb.append("请求耗时: ").append(detailedLog.getSpendTime()).append("\n");
        sb.append("响应状态: ").append(detailedLog.getResponseStatus()).append("\n");
        sb.append("响应数据: ").append(detailedLog.getResponseBody()).append("\n");
        sb.append("-----------------------------请求结束---------------------------------");
        sb.append("\n");
        synchronized (this) {
            log.info(sb.toString());
        }
    }


    public static int getSize() {
        return logQueue.size();
    }


    /**
     * @param detailedLog
     */
    public static void pushLog(DetailedLog detailedLog) {
        logQueue.offer(detailedLog);
    }


    public static DetailedLog popLog() {
        return logQueue.poll();
    }

}
